package com.hunliji.monitor.web.facade.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunliji.monitor.manager.api.FeiShuManager;
import com.hunliji.monitor.manager.api.GitlabManager;
import com.hunliji.monitor.manager.api.model.dto.gitlab.GitlabDiscussion;
import com.hunliji.monitor.manager.api.model.dto.gitlab.GitlabUser;
import com.hunliji.monitor.manager.api.model.param.FeiShuSendMsgManagerParam;
import com.hunliji.monitor.service.api.UserInfoService;
import com.hunliji.monitor.service.api.model.bo.FeishuPostMessageBO;
import com.hunliji.monitor.service.api.model.bo.UserInfoBO;
import com.hunliji.monitor.share.component.ComponentLocator;
import com.hunliji.monitor.share.enums.MsgTypeEnum;
import com.hunliji.monitor.share.enums.ReceiveIdTypeEnum;
import com.hunliji.monitor.share.utils.StringCommonUtil;
import com.hunliji.monitor.web.facade.FeiShuFacade;
import com.hunliji.monitor.web.facade.GitLabWebhookFacade;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam.MergeRequestBean;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam.MergeRequestBean.LastCommitBean;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam.MergeRequestBean.LastCommitBean.AuthorBean;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam.ObjectAttributesBean;
import com.hunliji.monitor.web.model.param.GitLabNoteHookParam.UserBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

/**
 * File：GitLabWebhookFacadeImpl.java<br> Title: <br> Description: <br>
 *
 * @author lejin Date: 2023/7/25
 */
@Component
@Slf4j
public class GitLabWebhookFacadeImpl implements GitLabWebhookFacade {

    @Resource
    UserInfoService userInfoService;
    @Resource
    FeiShuFacade feiShuFacade;
    @Resource
    FeiShuManager feiShuManager;
    @Resource
    GitlabManager gitlabManager;

    public void test(){
        String json = "{\n" +
                "  \"object_kind\": \"note\",\n" +
                "  \"event_type\": \"note\",\n" +
                "  \"user\": {\n" +
                "    \"id\": 22,\n" +
                "    \"name\": \"shang_yu\",\n" +
                "    \"username\": \"shang_yu\",\n" +
                "    \"avatar_url\": \"https://git.hunliji.com/uploads/-/system/user/avatar/22/avatar.png\",\n" +
                "    \"email\": \"shang_yu@hunliji.com\"\n" +
                "  },\n" +
                "  \"project_id\": 248,\n" +
                "  \"project\": {\n" +
                "    \"id\": 248,\n" +
                "    \"name\": \"product-develop-center\",\n" +
                "    \"description\": \"产研中心\",\n" +
                "    \"web_url\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "    \"avatar_url\": null,\n" +
                "    \"git_ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "    \"git_http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\",\n" +
                "    \"namespace\": \"商家端\",\n" +
                "    \"visibility_level\": 0,\n" +
                "    \"path_with_namespace\": \"merchant/product-develop-center\",\n" +
                "    \"default_branch\": \"master\",\n" +
                "    \"ci_config_path\": \"\",\n" +
                "    \"homepage\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "    \"url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "    \"ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "    \"http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\"\n" +
                "  },\n" +
                "  \"object_attributes\": {\n" +
                "    \"attachment\": null,\n" +
                "    \"author_id\": 22,\n" +
                "    \"change_position\": {\n" +
                "      \"base_sha\": null,\n" +
                "      \"start_sha\": null,\n" +
                "      \"head_sha\": null,\n" +
                "      \"old_path\": null,\n" +
                "      \"new_path\": null,\n" +
                "      \"position_type\": \"text\",\n" +
                "      \"old_line\": null,\n" +
                "      \"new_line\": null,\n" +
                "      \"line_range\": null\n" +
                "    },\n" +
                "    \"commit_id\": null,\n" +
                "    \"created_at\": \"2023-10-23 03:28:37 UTC\",\n" +
                "    \"discussion_id\": \"c4f84b759216b59ff24f2721d5665a0d8efac9f4\",\n" +
                "    \"id\": 20000,\n" +
                "    \"line_code\": \"9c00435c1c3f2568d69fd41d7c97ad353471c179_0_10\",\n" +
                "    \"note\": \"biubiu\",\n" +
                "    \"noteable_id\": 14301,\n" +
                "    \"noteable_type\": \"MergeRequest\",\n" +
                "    \"original_position\": {\n" +
                "      \"base_sha\": \"ee5544955192ced7ee8df207b0be538f6765c3e9\",\n" +
                "      \"start_sha\": \"b72eb67b3c73742dfa1c23c04dd36d469efb0c9a\",\n" +
                "      \"head_sha\": \"5ef920de59be928d5082850695702d859b917b60\",\n" +
                "      \"old_path\": \"product-develop-center-dao/src/main/java/com/hunliji/center/dao/mapper/bi/AutoTrackElementTagMappingDAO.java\",\n" +
                "      \"new_path\": \"product-develop-center-dao/src/main/java/com/hunliji/center/dao/mapper/bi/AutoTrackElementTagMappingDAO.java\",\n" +
                "      \"position_type\": \"text\",\n" +
                "      \"old_line\": null,\n" +
                "      \"new_line\": 10,\n" +
                "      \"line_range\": {\n" +
                "        \"start\": {\n" +
                "          \"line_code\": \"9c00435c1c3f2568d69fd41d7c97ad353471c179_0_10\",\n" +
                "          \"type\": \"new\",\n" +
                "          \"old_line\": null,\n" +
                "          \"new_line\": 10\n" +
                "        },\n" +
                "        \"end\": {\n" +
                "          \"line_code\": \"9c00435c1c3f2568d69fd41d7c97ad353471c179_0_10\",\n" +
                "          \"type\": \"new\",\n" +
                "          \"old_line\": null,\n" +
                "          \"new_line\": 10\n" +
                "        }\n" +
                "      }\n" +
                "    },\n" +
                "    \"position\": {\n" +
                "      \"base_sha\": \"ee5544955192ced7ee8df207b0be538f6765c3e9\",\n" +
                "      \"start_sha\": \"b72eb67b3c73742dfa1c23c04dd36d469efb0c9a\",\n" +
                "      \"head_sha\": \"5ef920de59be928d5082850695702d859b917b60\",\n" +
                "      \"old_path\": \"product-develop-center-dao/src/main/java/com/hunliji/center/dao/mapper/bi/AutoTrackElementTagMappingDAO.java\",\n" +
                "      \"new_path\": \"product-develop-center-dao/src/main/java/com/hunliji/center/dao/mapper/bi/AutoTrackElementTagMappingDAO.java\",\n" +
                "      \"position_type\": \"text\",\n" +
                "      \"old_line\": null,\n" +
                "      \"new_line\": 10,\n" +
                "      \"line_range\": {\n" +
                "        \"start\": {\n" +
                "          \"line_code\": \"9c00435c1c3f2568d69fd41d7c97ad353471c179_0_10\",\n" +
                "          \"type\": \"new\",\n" +
                "          \"old_line\": null,\n" +
                "          \"new_line\": 10\n" +
                "        },\n" +
                "        \"end\": {\n" +
                "          \"line_code\": \"9c00435c1c3f2568d69fd41d7c97ad353471c179_0_10\",\n" +
                "          \"type\": \"new\",\n" +
                "          \"old_line\": null,\n" +
                "          \"new_line\": 10\n" +
                "        }\n" +
                "      }\n" +
                "    },\n" +
                "    \"project_id\": 248,\n" +
                "    \"resolved_at\": null,\n" +
                "    \"resolved_by_id\": null,\n" +
                "    \"resolved_by_push\": null,\n" +
                "    \"st_diff\": null,\n" +
                "    \"system\": false,\n" +
                "    \"type\": \"DiffNote\",\n" +
                "    \"updated_at\": \"2023-10-23 03:28:37 UTC\",\n" +
                "    \"updated_by_id\": null,\n" +
                "    \"description\": \"biubiu\",\n" +
                "    \"url\": \"https://git.hunliji.com/merchant/product-develop-center/-/merge_requests/35#note_20000\"\n" +
                "  },\n" +
                "  \"repository\": {\n" +
                "    \"name\": \"product-develop-center\",\n" +
                "    \"url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "    \"description\": \"产研中心\",\n" +
                "    \"homepage\": \"https://git.hunliji.com/merchant/product-develop-center\"\n" +
                "  },\n" +
                "  \"merge_request\": {\n" +
                "    \"assignee_id\": null,\n" +
                "    \"author_id\": 23,\n" +
                "    \"created_at\": \"2023-10-23 03:26:35 UTC\",\n" +
                "    \"description\": \"\",\n" +
                "    \"head_pipeline_id\": null,\n" +
                "    \"id\": 14301,\n" +
                "    \"iid\": 35,\n" +
                "    \"last_edited_at\": null,\n" +
                "    \"last_edited_by_id\": null,\n" +
                "    \"merge_commit_sha\": null,\n" +
                "    \"merge_error\": null,\n" +
                "    \"merge_params\": {\n" +
                "      \"force_remove_source_branch\": \"1\"\n" +
                "    },\n" +
                "    \"merge_status\": \"cannot_be_merged\",\n" +
                "    \"merge_user_id\": null,\n" +
                "    \"merge_when_pipeline_succeeds\": false,\n" +
                "    \"milestone_id\": null,\n" +
                "    \"source_branch\": \"feature/gitlab的mr评论跟飞书打通\",\n" +
                "    \"source_project_id\": 248,\n" +
                "    \"state_id\": 1,\n" +
                "    \"target_branch\": \"dev\",\n" +
                "    \"target_project_id\": 248,\n" +
                "    \"time_estimate\": 0,\n" +
                "    \"title\": \"Feature/gitlab的mr评论跟飞书打通\",\n" +
                "    \"updated_at\": \"2023-10-23 03:28:37 UTC\",\n" +
                "    \"updated_by_id\": null,\n" +
                "    \"url\": \"https://git.hunliji.com/merchant/product-develop-center/-/merge_requests/35\",\n" +
                "    \"source\": {\n" +
                "      \"id\": 248,\n" +
                "      \"name\": \"product-develop-center\",\n" +
                "      \"description\": \"产研中心\",\n" +
                "      \"web_url\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "      \"avatar_url\": null,\n" +
                "      \"git_ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"git_http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\",\n" +
                "      \"namespace\": \"商家端\",\n" +
                "      \"visibility_level\": 0,\n" +
                "      \"path_with_namespace\": \"merchant/product-develop-center\",\n" +
                "      \"default_branch\": \"master\",\n" +
                "      \"ci_config_path\": \"\",\n" +
                "      \"homepage\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "      \"url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\"\n" +
                "    },\n" +
                "    \"target\": {\n" +
                "      \"id\": 248,\n" +
                "      \"name\": \"product-develop-center\",\n" +
                "      \"description\": \"产研中心\",\n" +
                "      \"web_url\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "      \"avatar_url\": null,\n" +
                "      \"git_ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"git_http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\",\n" +
                "      \"namespace\": \"商家端\",\n" +
                "      \"visibility_level\": 0,\n" +
                "      \"path_with_namespace\": \"merchant/product-develop-center\",\n" +
                "      \"default_branch\": \"master\",\n" +
                "      \"ci_config_path\": \"\",\n" +
                "      \"homepage\": \"https://git.hunliji.com/merchant/product-develop-center\",\n" +
                "      \"url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"ssh_url\": \"git@git.hunliji.com:merchant/product-develop-center.git\",\n" +
                "      \"http_url\": \"https://git.hunliji.com/merchant/product-develop-center.git\"\n" +
                "    },\n" +
                "    \"last_commit\": {\n" +
                "      \"id\": \"5ef920de59be928d5082850695702d859b917b60\",\n" +
                "      \"message\": \"测试接口\\n\",\n" +
                "      \"title\": \"测试接口\",\n" +
                "      \"timestamp\": \"2023-07-25T10:30:06+08:00\",\n" +
                "      \"url\": \"https://git.hunliji.com/merchant/product-develop-center/-/commit/5ef920de59be928d5082850695702d859b917b60\",\n" +
                "      \"author\": {\n" +
                "        \"name\": \"LeJin\",\n" +
                "        \"email\": \"le_jin@hunliji.com\"\n" +
                "      }\n" +
                "    },\n" +
                "    \"work_in_progress\": false,\n" +
                "    \"total_time_spent\": 0,\n" +
                "    \"time_change\": 0,\n" +
                "    \"human_total_time_spent\": null,\n" +
                "    \"human_time_change\": null,\n" +
                "    \"human_time_estimate\": null,\n" +
                "    \"assignee_ids\": [\n" +
                "\n" +
                "    ],\n" +
                "    \"state\": \"opened\"\n" +
                "  }\n" +
                "}";
        gitLabNoteHook(JSONObject.parseObject(json, GitLabNoteHookParam.class));
    }

    @Override
    public Boolean gitLabNoteHook(GitLabNoteHookParam param) {
        UserBean user = param.getUser();
        String email = user.getEmail();
        if(StringUtils.isBlank(email)){
            return false;
        }
        UserInfoBO userInfoBO = userInfoService.queryByMail(email);
        if(userInfoBO == null){
            return false;
        }
        MergeRequestBean mergeRequest = param.getMerge_request();
        if(mergeRequest == null){
            log.warn("mergeRequest is null");
            return false;
        }
        String mergeRequestTitle = mergeRequest.getTitle();
        Integer mergeRequestAuthorId = mergeRequest.getAuthor_id();
        if(mergeRequestAuthorId == null){
            log.warn("mergeRequestAuthorId is null");
            return false;
        }
        GitlabUser mergeAuthor = gitlabManager.getUserInfo(mergeRequestAuthorId);
        if(Objects.isNull(mergeAuthor)){
            log.warn("mergeAuthor is null");
            return false;
        }
        String email1 = mergeAuthor.getEmail();
        UserInfoBO authorUserInfoBO = userInfoService.queryByMail(email1);

        ObjectAttributesBean objectAttributes = param.getObject_attributes();
        String createdAt = objectAttributes.getCreated_at();
        if(StringUtils.isNotBlank(createdAt)){
            createdAt = createdAt.replace(" UTC", "");
        } else {
            log.warn("created_at is null");
        }
        String note = objectAttributes.getNote();
        String url = objectAttributes.getUrl();
        List<String> atUser = Optional.ofNullable(StringCommonUtil.getAtUser(note)).orElseGet(ArrayList::new);
        String discussionId = objectAttributes.getDiscussion_id();
        Integer mergeiid = param.getMerge_request().getIid();
        Integer projectId = param.getProject_id();
        GitlabDiscussion discussion = gitlabManager.getDiscussion(projectId, mergeiid, discussionId);
        List<String> allUserNames = discussion.getNotes()
                .stream()
                .map(k -> k.getAuthor())
                .map(k -> k.getUsername())
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(allUserNames)){
            atUser.addAll(allUserNames);
        }
        atUser.add(mergeAuthor.getUsername());
        // allUserIds 转换成对应的邮箱
       /* for (Integer userId : allUserIds) {
            String userEmail = ComponentLocator.getRedis().get("gitlab:user:email" + userId);
            if (StringUtils.isBlank(userEmail)){
                GitlabUser userInfo = gitlabManager.getUserInfo(userId);
                userEmail = userInfo.getEmail();
                ComponentLocator.getRedis().set("gitlab:user:email" + userId, userEmail, 60 * 60 * 24 * 7);
            }
            if (StringUtils.isNotBlank(userEmail)){
                atUser.add(userEmail);
            }
        }*/
        if(CollectionUtils.isNotEmpty(atUser)){
            //过滤掉作者自身
            atUser = atUser.stream().filter(x -> !Objects.equals(x + "@hunliji.com", user.getEmail())).distinct().collect(
                Collectors.toList());
            //通知被at的人
            notifyAtUser(atUser, mergeRequestTitle, userInfoBO, note, createdAt, authorUserInfoBO, url);
        }
        //通知作者
        //notifyUser(mergeRequestTitle, userInfoBO, note, createdAt, authorUserInfoBO, url);
        return true;
    }

    private void notifyUser(String mergeRequestTitle, UserInfoBO commentUserInfoBO, String note, String createdAt, UserInfoBO authorUser, String url){
        if(Objects.isNull(authorUser)){
            return;
        }
        FeishuPostMessageBO feishuPostMessageBO = FeishuPostMessageBO.getDefaultGitLabCommentPostMessageV2(
            mergeRequestTitle, note, url, createdAt, commentUserInfoBO);
        FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
            .receiveIdType(ReceiveIdTypeEnum.USER_ID.getCode())
            .receiveId(authorUser.getFeishuUserId())
            .content(JSON.toJSONString(feishuPostMessageBO))
            .msgType(MsgTypeEnum.POST.getCode()).build();
        feiShuManager.sendMsg(param, feiShuFacade.getGitLabAccessToken());
    }

    private void notifyAtUser(List<String> atUser, String mergeRequestTitle, UserInfoBO commentUserInfoBO, String note, String createdAt, UserInfoBO authorUser, String url){
        // authorUser 是MR的创建者
        atUser.forEach(user -> {
            String userMail = user + "@hunliji.com";
            UserInfoBO atUserInfoBO = userInfoService.queryByMail(userMail);
            if(Objects.nonNull(atUserInfoBO)){
                FeishuPostMessageBO feishuPostMessageBO = FeishuPostMessageBO.getDefaultGitLabCommentAtPostMessageV2(
                    mergeRequestTitle, note, url, createdAt, commentUserInfoBO, authorUser);
                FeiShuSendMsgManagerParam param = FeiShuSendMsgManagerParam.builder()
                    .receiveIdType(ReceiveIdTypeEnum.USER_ID.getCode())
                    .receiveId(atUserInfoBO.getFeishuUserId())
                    .content(JSON.toJSONString(feishuPostMessageBO))
                    .msgType(MsgTypeEnum.POST.getCode()).build();
                feiShuManager.sendMsg(param, feiShuFacade.getGitLabAccessToken());
            }
        });
    }
}
